package controllers

import (
	"fmt"
	"mime/multipart"
	"my-go-project/config"
	"my-go-project/model"
	"my-go-project/utils/token"
	"net/http"
	"os"
	"path"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

type UploadRequest struct {
	AuthorID       int64                   `json:"AuthorID"`
	City           *string                 `json:"city,omitempty"`
	Contact        *string                 `json:"Contact,omitempty"`
	ContactType    *string                 `json:"ContactType,omitempty"`
	PassageContent string                  `json:"PassageContent"`
	PassageTitle   string                  `json:"PassageTitle"`
	PassageType    string                  `json:"PassageType"`
	Province       *string                 `json:"Province,omitempty"`
	PassagePic     []*multipart.FileHeader `json:"PassagePic"`
}

type DeleteRequest struct {
	PassageID int64 `json:"PassageID"`
}

func UploadPassage(ctx *gin.Context) {
	// 接收图片文件
	// form, err := ctx.MultipartForm()
	// if err != nil {
	// 	ctx.JSON(http.StatusBadRequest, gin.H{
	// 		"error": "图片解析失败，请重试",
	// 	})
	// 	return
	// }

	var upload UploadRequest
	if err := ctx.ShouldBind(&upload); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"error": "请求体格式错误！",
		})
		return
	}

	// 更新联系方式
	if upload.Contact != nil && upload.ContactType != nil {
		err := model.UpdateContact(int(upload.AuthorID), *upload.Contact, *upload.ContactType)
		if err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": "联系方式更新错误！",
			})
			return
		}
	}

	// 上传文件内容
	currentTime := time.Now()
	formattedTime := currentTime.Format("2006-01-02 15:04:05")
	var passage model.Passage
	if upload.Province != nil && upload.City != nil {
		passage = model.Passage{
			AuthorID:       int(upload.AuthorID),
			PassageTitle:   upload.PassageTitle,
			PassagePic:     "default",
			PassageContent: upload.PassageContent,
			CommentNum:     0,
			LikeNum:        0,
			PassageTime:    formattedTime,
			PassageType:    upload.PassageType,
			PassageArea:    *upload.Province + " " + *upload.City,
		}
	} else {
		passage = model.Passage{
			AuthorID:       int(upload.AuthorID),
			PassageTitle:   upload.PassageTitle,
			PassagePic:     "default",
			PassageContent: upload.PassageContent,
			CommentNum:     0,
			LikeNum:        0,
			PassageTime:    formattedTime,
			PassageType:    upload.PassageType,
			// PassageArea:    *upload.Province + " " + *upload.City,
		}
	}
	pid, err := model.UploadPassage(passage)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": "文章发布失败！",
		})
		return
	}

	// 获取文章图片并上传
	dir := config.AppConfig.File.AbsolutePath + config.AppConfig.File.Path + strconv.Itoa(int(upload.AuthorID)) + "/" + strconv.Itoa(pid) + "/"
	ppp := config.AppConfig.File.Path + strconv.Itoa(int(upload.AuthorID)) + "/" + strconv.Itoa(pid) + "/"
	err = os.MkdirAll(dir, 0777)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": "图片上传失败，请重试",
		})
		return
	}
	files := upload.PassagePic // form.File["PassagePic"]
	for i, file := range files {
		fmt.Println("原始文件：", file.Filename)
		extName := path.Ext(file.Filename)
		fmt.Println("文件后缀名：", extName)
		dst := path.Join(dir, strconv.Itoa(i)+extName)
		fmt.Println("文件存储路径：", dst)
		if err := ctx.SaveUploadedFile(file, dst); err != nil {
			ctx.JSON(http.StatusInternalServerError, gin.H{
				"error": err.Error(),
			})
			return
		}
	}
	uperr := model.UpdateArea(pid, ppp)
	if uperr != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": "图片上传失败1，请重试",
		})
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"Response": "文章发布成功！",
	})
}

func DeletePassage(ctx *gin.Context) {
	var delete DeleteRequest
	if err := ctx.ShouldBindBodyWithJSON(&delete); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"error": "请求体格式错误！",
		})
		return
	}

	uid, err := token.ExtractTokenID(ctx)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": err.Error(),
		})
		return
	}

	if err := model.DeletePassage(int(delete.PassageID)); err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": "文章删除失败！",
		})
		return
	}

	path := config.AppConfig.File.Path + strconv.Itoa(int(uid)) + "/" + strconv.Itoa(int(delete.PassageID)) + "/"
	err = os.RemoveAll(path)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"error": "文章图片删除失败！",
		})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"Response": "文章删除成功！",
	})
}
